import { NextResponse } from 'next/server'
import prisma from '@/lib/db'
import { verifyToken } from '@/lib/auth'

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { id } = params
    
    const topic = await prisma.productTopic.findUnique({
      where: { id }
    })
    
    if (!topic) {
      return new Response(
        JSON.stringify({ error: '未找到话题' }),
        { status: 404 }
      )
    }


    await prisma.productTopic.delete({
      where: { id }
    })
    // 删除话题对应的所有文案
    await prisma.productCopy.deleteMany({
      where: { topic_id: id }
    })


    return new Response(
      JSON.stringify({ message: '话题删除成功' }),
      { status: 200 }
    )
  } catch (error: any) {
    return new Response(
      JSON.stringify({ error: error.message || '删除话题失败' }),
      { status: 500 }
    )
  }
}

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const { id } = params
    
    const topic = await prisma.productTopic.findUnique({
      where: { id }
    })
    
    if (!topic) {
      return new Response(
        JSON.stringify({ error: '未找到话题' }),
        { status: 404 }
      )
    }
    
    return new Response(
      JSON.stringify(topic),
      { status: 200 }
    )
  } catch (error: any) {
    return new Response(
      JSON.stringify({ error: error.message || '获取详情失败' }),
      { status: 500 }
    )
  }
}